/*
 * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.wso2.carbon.registry.lifecycle.accenture.sample.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.registry.common.eventing.RegistryEvent;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.session.CurrentSession;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.core.UserStoreManager;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.NetworkUtils;

import java.net.SocketException;

public class NotificationUtil {
    private static final Log log = LogFactory.getLog(NotificationUtil.class);

    /**
     * This method used to send messages when service states are change
     *
     * @param event    Registry event
     * @param registry Registry
     * @param path     that need to be send events
     * @throws Exception if failed the notification
     */
    public static void notify(RegistryEvent<String> event, Registry registry, String path) throws Exception {
        try {
            if (Utils.getRegistryNotificationService() == null) {
                log.error("Eventing service is unavailable.");
                return;
            }
            if (registry == null || registry.getEventingServiceURL(path) == null) {
                Utils.getRegistryNotificationService().notify(event);
                return;
            } else if (Utils.getDefaultNotificationServiceURL() == null) {
                log.error("ServiceRequestLifecycle Eventing Handler is not properly initialized");
            } else if (registry.getEventingServiceURL(path).equals(Utils.getDefaultNotificationServiceURL())) {
                Utils.getRegistryNotificationService().notify(event);
                return;
            } else {
                System.out.println("Notified:" + event.getMessage());
                Utils.getRegistryNotificationService().notify(event, registry.getEventingServiceURL(path));
                return;
            }
        } catch (RegistryException e) {
            log.error("Unable to send notification", e);
        }
        log.error("Unable to send notification");
    }

    /**
     * This class used to get backEnd Server URL.
     *
     * @return
     */
    public static String getBackendServerUrl() {
        String backEndURL = null;
        try {
            backEndURL = "https://" + NetworkUtils.getLocalHostname() + ":" +
                    CarbonUtils.getTransportPort(Utils.getConfigurationContextService(), "https") +
                    Utils.getConfigurationContextService().getServerConfigContext().getContextRoot();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return backEndURL;
    }

    public static String getLoggedInUserEmail() {
        String email;
        UserRealm userRealm = CurrentSession.getUserRealm();
        String user = CurrentSession.getUser();
        UserStoreManager userStoreManager;
        if (userRealm != null) {
            try {
                userStoreManager = userRealm.getUserStoreManager();
                if (userStoreManager != null) {
                    String[] userProfiles = userStoreManager.getProfileNames(user);
                    for (String profile : userProfiles) {
                     email = userStoreManager.getUserClaimValue(CurrentSession.getUser(),"email",profile);
                        if(email!=null){
                            return email;
                        }
                    }
                }
            } catch (UserStoreException e) {
                e.printStackTrace();
            }
        } else {
            log.error("Failed to get email for user");
        }
       return null;
    }
}
